<template>
  <div class="component-container">
    <div class="nav">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/bms-switchList' }">设备管理</el-breadcrumb-item>
        <el-breadcrumb-item>设备详情{{gateway ? '网关' : ''}}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="device-detail-content">
      <div class="header" v-loading="loadingSwitchInfo">
        <div class="title">
          <h1>{{switchInfo.name}}</h1>
          <span>{{switchInfo.status === 1 || switchInfo.status === 2 ? '在线' : '离线'}}</span>
        </div>
        <div class="switch-info">
          <div class="switch-info-attribute">
            <span class="attribute-name">产品：</span>
            <span class="attribute-value">{{switchInfo.productName}}</span>
          </div>
          <div class="switch-info-attribute">
            <span class="attribute-name">ProductKey：</span>
            <span class="attribute-value">{{switchInfo.productKey}}</span>
          </div>
        </div>
      </div>
      <div class="content">
        <div class="content-item" v-loading="loadingSwitchInfo">
          <div class="title">设备信息</div>
          <div>
            <el-row>
              <el-col :span="3"><span>iotId</span></el-col>
              <el-col :span="5">
                <el-popover
                  placement="top"
                  trigger="hover"
                  :content="switchInfo.iotId">
                  <span slot="reference">{{switchInfo.iotId}}</span>
                </el-popover>
              </el-col>
              <el-col :span="3"><span>设备名</span></el-col>
              <el-col :span="5"><span>{{switchInfo.name}}</span></el-col>
              <el-col :span="3"><span>地区</span></el-col>
              <el-col :span="5"><span>{{switchInfo.region}}</span></el-col>
            </el-row>
            <el-row>
              <el-col :span="3"><span>类型</span></el-col>
              <el-col :span="5"><span>{{switchInfo.productName}}</span></el-col>
              <el-col :span="3"><span>状态</span></el-col>
              <el-col :span="5"><span>{{switchInfo.status === 1 || switchInfo.status === 2 ? '在线' : '离线'}}</span></el-col>
              <el-col :span="3"><span>固件版本号</span></el-col>
              <el-col :span="5"><span>{{switchInfo.firmwareVersion ? switchInfo.firmwareVersion : '-'}}</span></el-col>
            </el-row>
            <el-row>
              <el-col :span="3"><span>设备操作日期</span></el-col>
              <el-col :span="5"><span>{{formatTime(switchInfo.gmtModified, 'Y/M/D h:m:s')}}</span></el-col>
              <el-col :span="3"><span>设备激活日期</span></el-col>
              <el-col :span="5"><span>{{formatTime(switchInfo.activeTime, 'Y/M/D h:m:s')}}</span></el-col>
              <el-col :span="3"><span>设备创建日期</span></el-col>
              <el-col :span="5"><span>{{formatTime(switchInfo.gmtCreate, 'Y/M/D h:m:s')}}</span></el-col>
            </el-row>
          </div>
        </div>
        <div class="content-item" v-if="!gateway">
          <div class="title">设备状态变更记录查询</div>
          <div class="search-bar">
            <span>
              <el-select v-model="searchData.identifier" placeholder="请选择设备属性" style="width: 220px;" clearable v-loading="loadingSwitchProperties">
                <el-option
                  :value="properties.attribute"
                  v-for="(properties, index) in switchPropertiesList"
                  :key="index"
                ></el-option>
              </el-select>
            </span>
            <div class="date-wrapper">
              <el-col :span="11">
                <el-date-picker type="date" placeholder="请选择起始日期" v-model="searchData.start" value-format="timestamp" :clearable="false" style="width: 100%;"></el-date-picker>
              </el-col>
              <el-col class="line" :span="2">-</el-col>
              <el-col :span="11">
                <el-date-picker placeholder="请选择截止日期" v-model="searchData.end" value-format="timestamp" :clearable="false" style="width: 100%;"></el-date-picker>
              </el-col>
            </div>
            <span>
              <el-button plain @click="getReportList">搜索</el-button>
            </span>
          </div>
          <div style="max-height: 300px; overflow: auto;">
            <el-table :data="reportList" style="width: 100%" v-loading="loadingReportList">
              <el-table-column type="index" label="序号" width="55"></el-table-column>
              <el-table-column prop="property" label="属性" min-width="200"></el-table-column>
              <el-table-column prop="data" label="属性值" min-width="150"></el-table-column>
              <el-table-column label="更新时间" min-width="200">
                <template slot-scope="scope">
                  <span>{{formatTime(scope.row.timestamp, 'Y/M/D h:m:s')}}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div class="content-item" v-if="gateway">
          <div class="title">网关下属设备列表</div>
          <div>
            <el-table :data="subSwitchList" style="width: 100%" v-loading="loadingSubSwitchList">
              <el-table-column type="index" label="序号" width="55"></el-table-column>
              <el-table-column prop="deviceName" label="设备名" min-width="200"></el-table-column>
              <el-table-column label="设备类型" min-width="150">
                <template slot-scope="scope">
                  <div v-for="product in productList" :key="product.productkey">
                    <span v-if="product.productkey === scope.row.productKey">{{product.name}}</span>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      iotId: '',
      gateway: false,
      switchInfo: {},
      switchPropertiesList: [],
      subSwitchList: [],
      reportList: [],
      searchData: {
        start: '',
        end: '',
        identifier: '',
      },
      productList: [],
      loadingSwitchInfo: true,
      loadingSubSwitchList: true,
      loadingSwitchProperties: true,
      loadingReportList: false,
    };
  },
  components: {},
  mounted () {
    this.productList = JSON.parse(window.sessionStorage.getItem('productList'))
    this.iotId = this.$route.query.iotId
    this.gateway = JSON.parse(this.$route.query.gateway)
    this.getSearchTime()
    this.getSwitchInfo()
    this.gateway ? this.getSubSwitchList() : this.getSwitchProperties()
  },
  methods: {
    //获取查询起始日期时间戳
    getSearchTime() {
      let date = new Date();
      let year = date.getFullYear();
      let mouth = date.getMonth() + 1;
      let day = date.getDate();
      let today = year + '-' + mouth + '-' + day;
      let lastYearToday = (year-1) + '-' + mouth + '-' + day;
      this.searchData.start = new Date(lastYearToday).getTime();
      this.searchData.end = new Date(today).getTime();
    },
    //获取设备详情
    async getSwitchInfo() {
      this.loadingSwitchInfo = true;
      let {data: res} = await this.$http.post("bms/switch/info", { iotId: this.iotId })
      if (res.resultCode !== "000") return this.$message.error(res.resultMessage);
      this.productList.forEach(product => {
        if(product.productkey === res.data.productKey) res.data.productName = product.name
      })
      this.switchInfo = res.data
      this.loadingSwitchInfo = false;
    },
    /** 
     * 时间戳转化为年 月 日 时 分 秒 
     * number: 传入时间戳 
     * format：返回格式，支持自定义，但参数必须与formateArr里保持一致 
    */  
    formatTime(number, format) {
      if(!number) return '-'
      var formateArr  = ['Y','M','D','h','m','s'];  
      var returnArr   = [];  
      
      var date = new Date(Number(number));  
      returnArr.push(date.getFullYear());  
      returnArr.push(this.formatNumber(date.getMonth() + 1));  
      returnArr.push(this.formatNumber(date.getDate()));  
      
      returnArr.push(this.formatNumber(date.getHours()));  
      returnArr.push(this.formatNumber(date.getMinutes()));  
      returnArr.push(this.formatNumber(date.getSeconds()));  
      
      for (var i in returnArr) {  
        format = format.replace(formateArr[i], returnArr[i]);  
      }  
      return format;  
    },
    //数据转化  
    formatNumber(n) {  
      n = n.toString()  
      return n[1] ? n : '0' + n  
    },
    //获取设备属性
    async getSwitchProperties() {
      this.loadingSwitchProperties = true;
      let {data: res} = await this.$http.post("bms/switch/properties", { iotId: this.iotId })
      if (res.resultCode !== "000") return this.$message.error(res.resultMessage);
      this.switchPropertiesList = res.data ? res.data.filter( item => item.attribute !== "CountDown" && item.attribute !== "CountDownList" && item.attribute !== "LocalTimer" ) : []
      this.loadingSwitchProperties = false;
    },
    //获取设备属性变更历史记录
    async getReportList() {
      this.loadingReportList = true;
      if(!this.searchData.identifier) return this.$message.error("请选择设备属性")
      if(!this.searchData.start) return this.$message.error("请选择起始日期")
      if(!this.searchData.end) return this.$message.error("请选择截止日期")
      if (this.searchData.start > this.searchData.end) return this.$message.error("起始日期应小于或等于截止日期")
      let {data: res} = await this.$http.post("bms/switch/properties/timeline?identifier="+this.searchData.identifier+"&start="+this.searchData.start+"&end="+(this.searchData.end + 24*60*60*1000-1)+"&pageSize=200&ordered=true", { iotId: this.iotId })
      if (res.resultCode !== "000") return this.$message.error(res.resultMessage);
      this.reportList = !res.data ? [] : res.data
      this.reportList.forEach(item => {
        if(typeof item.data === 'object') item.data = JSON.stringify(item.data)
      })
      this.loadingReportList = false;
    },
    //获取下属设备列表
    async getSubSwitchList() {
      this.loadingSubSwitchList = true
      let {data: res} = await this.$http.post("bms/switch/subdev", { iotId: this.iotId })
      if (res.resultCode !== "000") return this.$message.error(res.resultMessage);
      this.subSwitchList = res.data
      this.loadingSubSwitchList = false
    },
  }
}
</script>

<style lang='scss' scoped>
.component-container {
  min-width: 1000px;
  height: calc(100vh - 50px);
  color: #333333;
  .nav {
    height: 60px;
    line-height: 60px;
    padding-left: 20px;
    display: flex;
    align-items: center;
  }
  .device-detail-content {
    .header {
      padding: 20px;
      .title {
        height: 32px;
        line-height: 32px;
        display: flex;
        h1 {
          font-size: 20px;
          margin: 0 8px 0 0;
        }
        span {
          font-size: 14px;
          font-weight: 400;
          color: #333333;
          background-color: #ecedee;
          display: inline-block;
          padding: 0 8px;
          border-radius: 5px;
        }
      }
      .switch-info {
        margin-top: 16px;
        display: flex;
        .switch-info-attribute {
          flex: 1;
          line-height: 28px;
          display: flex;
          align-items: center;
          .attribute-name {
            color: #999;
            margin-right: 8px;
          }
          .attribute-value {
            color: #666;
            margin-right: 8px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            display: inline-block;
          }
        }
      }
    }
    .content {
      background-color: #F7F7F7;
      padding: 20px 0;
      .content-item {
        background-color: #FFF;
        padding: 20px;
        margin-bottom: 20px;
        .title {
          font-size: 16px;
          font-weight: 700;
          color: #373d41;
          margin-bottom: 16px;
        }
        .el-row {
          border-bottom: 1px solid #ecedee;
          border-right: 1px solid #ecedee;
          &:first-child {
            border-top: 1px solid #ecedee;
          }
          .el-col {
            border-left: 1px solid #ecedee;
            height: 48px;
            line-height: 24px;
            display: flex;
            align-items: center;
            padding: 0 12px;
            text-align: center;
            &:nth-child(odd) {
              background-color: #fbfbfc;
            }
            span {
              margin: auto;
              width: 100%;
              overflow: hidden;
              text-overflow: ellipsis;
            }
          }
        }
        .search-bar {
          display: flex;
          margin: 20px 0 16px;
          > span {
            margin-right: 12px;
          }
          .date-wrapper {
            margin: 0 20px;
            width: 480px;
            text-align: center;
            line-height: 36px;
          }
        }
      }
    }
  }
}
</style>